﻿/**
 * ...
 * @author sminutoli
 */

import mx.utils.Delegate;
 
class com.dmotiko.lib.ControlFrameMovie 
{
	
	public static function createControl( root:MovieClip ):MovieClip {
		if ( ! root ) root = _root;
		var sName:String = "controlFrame";
		var nCount:Number = 0;
		while ( root[sName + nCount] ) {
			nCount++;
		}
		var frameControl = root.createEmptyMovieClip(sName + nCount, root.getNextHighestDepth() );
		frameControl.forward = function( args ) {
			//trace("ControlFrameMovie | forward called ");
			var clip:MovieClip = args.clip;
			var nInit:Number = args.init ? args.init : clip._currentFrame;
			var nEnd:Number = args.end ? args.end : clip._totalFrames;
			if ( args.init ) clip.gotoAndStop( nInit );
			
			this.onEnterFrame = function() {
				//trace("ControlFrameMovie | forward | clip "+clip+" current= "+clip._currentFrame+" forward end= "+nEnd);
				if ( clip._currentFrame >= nEnd ) {
					//trace("ControlFrameMovie | forward end ");
					delete this.onEnterFrame;
					Delegate.create( args.bind, args.listener )();
					if ( args.keepAlive == false ) this.removeMovieClip();
					return;
				}
				
				clip.nextFrame();
			}
		}
		frameControl.rewind = function( args ) {
			//trace("ControlFrameMovie | rewind called ");
			var clip:MovieClip = args.clip;
			var nInit:Number = args.init ? args.init : clip._currentFrame;
			var nEnd:Number = args.end ? args.end : 1;
			if ( args.init ) clip.gotoAndStop( nInit );
			
			this.onEnterFrame = function() {
				//trace("ControlFrameMovie | rewind | clip "+clip+" current= "+clip._currentFrame+" rewind end= "+nEnd);
				if ( clip._currentFrame <= nEnd ) {
					delete this.onEnterFrame;
					Delegate.create( args.bind, args.listener )();
					if ( args.keepAlive == false ) this.removeMovieClip();
					return;
				}
				clip.prevFrame();
			}
		}
		
		return frameControl;
	}
	
}